package com.liuhangkai.firstpro.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.rmi.ServerException;
import java.sql.SQLException;


@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler({Exception.class, IOException.class, ServerException.class})
    public Object handleException(Exception e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错1-";
        }
        System.out.println(msg);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", msg);
        return jsonObject;
    }

    /**
     * 自定义验证异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", e.getMessage());
        return jsonObject;
    }

    /**
     * sql异常
     */
    @ExceptionHandler(SQLException.class)
    public Object sqlException(SQLException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", e.getMessage());
        return jsonObject;
    }

    /**
     * sql语法错误异常
     */
    @ExceptionHandler(DataAccessException.class)
    public Object dataAccessException(DataAccessException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", e.getMessage());
        return jsonObject;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Object validatedBindException(BindException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", e.getMessage());
        return jsonObject;
    }
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Object businessException(CustomException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", e.getMessage());
        jsonObject.put("CODE", e.getCode());
        return jsonObject;
    }
}
